// 字符串相似度计算
export const levenshteinDistance = (str1, str2) => {
  const matrix = [];
  for (let i = 0; i <= str2.length; i++) matrix[i] = [i];
  for (let j = 0; j <= str1.length; j++) matrix[0][j] = j;

  for (let i = 1; i <= str2.length; i++) {
    for (let j = 1; j <= str1.length; j++) {
      matrix[i][j] =
        str2[i - 1] === str1[j - 1]
          ? matrix[i - 1][j - 1]
          : Math.min(
              matrix[i - 1][j - 1] + 1,
              matrix[i][j - 1] + 1,
              matrix[i - 1][j] + 1
            );
    }
  }
  return matrix[str2.length][str1.length];
};

// 查找最相似的变量
export const findBestMatch = (target, candidates) => {
  if (!candidates.length) return null;
  const filtered = candidates.filter((c) => c !== "this");
  let bestMatch = null,
    bestScore = Infinity;

  for (const candidate of filtered) {
    const distance = levenshteinDistance(target, candidate);
    const similarity = 1 - distance / Math.max(target.length, candidate.length);
    if (similarity > 0.6 && distance < bestScore) {
      bestScore = distance;
      bestMatch = candidate;
    }
  }
  return bestMatch;
};

// 变量替换逻辑
export const performReplacement = (content, invalidVar, suggestion) => {
  const escaped = invalidVar.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  let newContent = content;

  // 替换简单变量
  newContent = newContent.replace(
    new RegExp(`\\{\\{\\s*${escaped}\\s*\\}\\}`, "g"),
    `{{${suggestion}}}`
  );
  // 替换#each变量
  newContent = newContent.replace(
    new RegExp(`\\{\\{\\s*#each\\s+${escaped}\\s*\\}\\}`, "g"),
    `{{#each ${suggestion}}}`
  );
  // 替换#if变量
  newContent = newContent.replace(
    new RegExp(`(\\b#if\\s+)${escaped}(?!\\w)`, "g"),
    `$1${suggestion}`
  );
  // 替换this.变量
  newContent = newContent.replace(
    new RegExp(`(\\{\\{this\\.)${escaped}(?!\\w)`, "g"),
    `$1${suggestion}`
  );

  return newContent;
};

// 默认Markdown模板
export const getDefaultMarkdownTemplate = () => `# {{schemeName}}

## 1. 工程概况
- **项目名称**: {{projectName}}
- **跨越点**: {{crossing_name}}
- **跨越类型**: {{crossing_crossingType_label}}

## 2. 施工方法
{{scheme_constructionMethod}}

## 3. 施工步骤
{{#each scheme_constructionSteps}}
### 步骤{{index_plus_1}}: {{stepName}}
{{description}}
{{/each}}

## 4. 安全措施
{{#each scheme_schemeLevelSafetyMeasures}}
- {{.}}
{{/each}}
`;

// 示例目录结构
export const getExampleOutline = () => `1. 工程概况
1.1 项目基本信息
1.2 跨越点基本信息
1.3 编制依据

2. 施工部署
2.1 施工方法选择
2.2 施工步骤
2.3 进度安排

3. 资源配置
3.1 人员配置
3.2 材料配置
3.3 机械设备配置

4. 安全措施
4.1 一般安全措施
4.2 专项安全措施
4.3 应急预案

5. 质量保证措施
5.1 质量目标
5.2 质量保证体系
5.3 质量检查要点

6. 环境保护措施
6.1 环保目标
6.2 环保措施
6.3 文明施工

7. 验收要求
7.1 验收标准
7.2 验收程序
7.3 验收资料`;
